//
//  HomeViewController.m
//  test
//
//  Created by 朱圳 on 2017/12/27.
//  Copyright © 2017年 朱圳. All rights reserved.
//

#import "HomeViewController.h"
#import "HomeViewHead.h"
#import "PlanHeadCell.h"
#import "PlanCell.h"
#import "PlanModelFrame.h"
#import "PlanModel.h"
#import "HomePlanClassNameCell.h"
#import "YHSTHomeFoot.h"
#import "UIImage+ExtenS.h"//image分类
static NSString *const cellIdtentifier = @"HomePlanClassNameCell";

@interface HomeViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong) HomeViewHead *homeViewHeadView;
@property(nonatomic,strong)UIView *noDataView;
@property(nonatomic,strong) PlanModel *model;
@property(nonatomic,strong)NSMutableArray <PlanModel *>* planArray;
@property(nonatomic,strong)NSMutableArray <ContentModel *>* contentArray;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,assign)int counts;

@property (nonatomic, strong) NSString * Newdays;
@property (nonatomic, strong) UITextField *DayTextField;


@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.homeViewHeadView];

    self.view.backgroundColor = [UIColor whiteColor];
    [self requestPlanData];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self requestPlanData];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

//请求首页网络数据
-(void)requestPlanData{
    __weak typeof(self) weakSelf = self;
    NSDictionary *dict = @{
                           @"sid" : Sid,
                           @"spass" : Spassword,
                           };
    [[AFNetworkTool shareManager]postJSONWithUrl:Studen_Index parmas:dict successData:^(id json) {
            [self.tableView.mj_header endRefreshing];
        if ([json[@"message"]isEqualToString:@"success"]) {
            [self.dataArray removeAllObjects];
            self.model = [PlanModel yy_modelWithJSON:json];
            //存days
            NSUserDefaults *userDefaults =[NSUserDefaults standardUserDefaults];
            [userDefaults setObject:json[@"days"] forKey:@"days"];
            //存考研倒计时
            NSUserDefaults *userDefaultDoun =[NSUserDefaults standardUserDefaults];
            [userDefaultDoun setObject:json[@"countdown"] forKey:@"countdown"];
            
           self.homeViewHeadView.model = self.model;
            NSArray *arr = json[@"list"];
            self.dataArray = [NSMutableArray array];
            for (NSDictionary * dic in arr) {
               PlanModel * model = [PlanModel yy_modelWithJSON:dic];
               PlanModelFrame * modelFrame = [[PlanModelFrame alloc]init];
                modelFrame.model = model;
                [self.dataArray addObject:modelFrame];
                
                if (modelFrame.model.list.count > 0) {
                    self.counts = self.counts + 1;
                    NSLog(@">>>>>%d", self.counts);
                }
            }
            if (self.counts > 0) {
              //  NSLog(@">>>>有数组");
            }else{
             //   NSLog(@">>>>无数组");
                //移除tableView添加无数据
                [self.tableView removeFromSuperview];
                [self.view addSubview:self.noDataView];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            self.Newdays=Days;
            [weakSelf.tableView reloadData];
        });
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
        [Utility showFail:@"网络连接出错..."];
        NSLog(@"error%@",error);
    }];
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}
/** 区头视图 */
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (self.counts > 0) {
      PlanHeadCell *header = [[PlanHeadCell alloc] initWithReuseIdentifier:@"planHeadCell"];
        return header;
    }else{
        return nil;
    }

}
#pragma -mark ————————————————————加载footer————————————————————

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    YHSTHomeFoot *footer=[[YHSTHomeFoot alloc]init];
    [footer.Addbtn addTarget:self action:@selector(AddbtnAction:) forControlEvents:UIControlEventTouchUpInside];
    //颜色图片
     UIImage *Coimage=[UIImage imageFromColor:HWColor(125, 125, 125)];
    [footer.Addbtn setBackgroundImage:Coimage forState:UIControlStateSelected];
    
    [footer.ReBtn addTarget:self action:@selector(ReBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [footer.LookBtn addTarget:self action:@selector(LookBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.DayTextField=footer.ShowDayField;
   
    
    return footer;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 40;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HomePlanClassNameCell *cell = [HomePlanClassNameCell cellWithTableView:tableView withReuseIdentifier:cellIdtentifier];
    cell.modelFrame = self.dataArray[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PlanModelFrame *modelFrame = self.dataArray[indexPath.row];
    return modelFrame.cellHeight;
}
#pragma mark - 懒加载
-(NSMutableArray *)planArray{
    if (!_planArray) {
        _planArray=[[NSMutableArray alloc]init];
    }
    return _planArray;
}
-(NSMutableArray *)contentArray{
    if (!_contentArray) {
        _contentArray=[[NSMutableArray alloc]init];
    }
    return _contentArray;
}
-(HomeViewHead *)homeViewHeadView{
    
    if (!_homeViewHeadView) {
        _homeViewHeadView = [[HomeViewHead alloc]initWithFrame:CGRectMake(0, Navigation_Bar_Height, ScreenWidth, 80)];
    }
    return _homeViewHeadView;
}

-(UITableView *)tableView{
    if (!_tableView) {
//        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, Navigation_Bar_Height+80+10, ScreenWidth, ScreenHeight-(Navigation_Bar_Height+80+10))];
        
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, Navigation_Bar_Height+80+10, ScreenWidth, ScreenHeight-(Navigation_Bar_Height+80+10)) style:UITableViewStyleGrouped];
        
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        [_tableView registerClass:[PlanHeadCell class] forHeaderFooterViewReuseIdentifier:@"planHeadCell"];
        [_tableView registerClass:[HomePlanClassNameCell class] forCellReuseIdentifier:cellIdtentifier];
    }
    return _tableView;
}

-(UIView *)noDataView{

    if (!_noDataView) {
        _noDataView = [[UIView alloc]initWithFrame:CGRectMake(0, Navigation_Bar_Height+80+10, ScreenWidth, 60)];
        _noDataView.backgroundColor = [UIColor whiteColor];
        UIImageView *imageView = [[UIImageView alloc]init];
        imageView.image = [UIImage imageNamed:@"NoData"];
        [_noDataView addSubview:imageView];
        
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(self->_noDataView);
            make.top.mas_equalTo(50);
            make.width.mas_equalTo(100);
            make.height.mas_equalTo(100);
        }];
        
        UILabel * la = [[UILabel alloc]init];
        la.text = @"亲,暂时没有计划信息!";
        la.textColor = [UIColor darkGrayColor];
        la.textAlignment = NSTextAlignmentCenter;
        [_noDataView addSubview:la];
        [la mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(self->_noDataView);
            [make.top.mas_equalTo(imageView.mas_bottom) setOffset:10];
            make.width.mas_equalTo(200);
        }];
    }
    return _noDataView;
}
#pragma -mark —————————————————footer事件————————————————————
//下一天
-(void)AddbtnAction:(UIButton *)Nexsend{
    
    
    if(self.Newdays==nil || self.Newdays==Days){
        NSString *days=Days;
        int Value=days.intValue+1;
        
        NSString *str=[NSString stringWithFormat:@"%d",Value];
        self.Newdays=str;
    }else{
        int Value2=self.Newdays.intValue+1;
        if(Value2>365){
            Value2=1;
        }
        NSString *str=[NSString stringWithFormat:@"%d",Value2];
        self.Newdays=str;
    }
    
    NSLog(@"--self.Newdays--%@", self.Newdays);
    [self setdata:self.Newdays:Nexsend];
    
   

}
//上一天
-(void)ReBtnAction:(UIButton *)Lssend{
    
    
    if(self.Newdays==nil || self.Newdays==Days){
        NSString *days=Days;
        int Value=days.intValue-1;
        
        NSString *str=[NSString stringWithFormat:@"%d",Value];
        self.Newdays=str;
    }else{
        int Value2=self.Newdays.intValue-1;
        if(Value2<1){
            Value2=365;
        }
        NSString *str=[NSString stringWithFormat:@"%d",Value2];
        self.Newdays=str;
    }
    
    NSLog(@"--aaaa--%@", self.Newdays);
    [self setdata:self.Newdays :Lssend];
}
//查看
-(void)LookBtnAction:(UIButton *)Looksend{
    //获取第1个输入框；
    
    if ([self.DayTextField.text intValue] > 365) {
        self.DayTextField.text = @"365";
    }
    if ([self.DayTextField.text intValue] < 1) {
        self.DayTextField.text = @"1";
    }
    self.Newdays = self.DayTextField.text;
    
    [self.view endEditing:YES];
    NSLog(@"--Newdays--%@",  self.Newdays);

    [self setdata:self.Newdays :Looksend];
}
//请求数据
-(void)setdata :(NSString *)Day :(UIButton *)send{
    send.userInteractionEnabled=NO;
    [EasyShowLodingView showLodingText:@""];
   
    __weak typeof(self) weakSelf = self;
    NSDictionary *dict = @{
                           @"sid" : Sid,
                           @"spass" : Spassword,
                           @"days" : Day,
                           };
    [[AFNetworkTool shareManager]postJSONWithUrl:Stu_Clock parmas:dict successData:^(id json) {
        
        if ([json[@"message"]isEqualToString:@"success"]) {
            
//                [self.view addSubview:self.tableView];
//                [self.view addSubview:self.homeViewHeadView];
            [self.dataArray removeAllObjects];
            self.model = [PlanModel yy_modelWithJSON:json];
            //赋值
            self.Newdays=json[@"days"];
            self.homeViewHeadView.model = self.model;

            NSArray *arr = json[@"list"];
            self.dataArray = [NSMutableArray array];
            for (NSDictionary * dic in arr) {
                PlanModel * model = [PlanModel yy_modelWithJSON:dic];
                PlanModelFrame * modelFrame = [[PlanModelFrame alloc]init];
                modelFrame.model = model;
                [self.dataArray addObject:modelFrame];
               
                if (modelFrame.model.list.count > 0) {
                    self.counts = self.counts + 1;
                    NSLog(@">>>>>%d", self.counts);
                }
            }
            if (self.counts > 0) {
                //  NSLog(@">>>>有数组");
            }else{
                //   NSLog(@">>>>无数组");
                //移除tableView添加无数据
                [self.tableView removeFromSuperview];
                [self.view addSubview:self.noDataView];
            }
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [EasyShowLodingView hidenLoding];
             send.userInteractionEnabled=YES;
            [weakSelf.tableView reloadData];
        });

    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
        [Utility showFail:@"网络连接出错..."];
        NSLog(@"error%@",error);
    }];
    
    
}

@end
